from flask_restful import Resource

from model.crud import QueryOneInstance, UpdateInstance
from model.tables import Blog, NowStr, User
from restful.data import DataText, DataPid, DataDisableUntil, DataUid
from restful.error import RenderPostNotExist
from restful.response import ResponseSuccess
from restful.session import current_user_is_admin_required,data


class AdminCheck(Resource):
    @current_user_is_admin_required
    def get(self,current_user):
        blogs = Blog.query.filter_by(checked=False).order_by(Blog.time.desc()).limit(10).all()

        return ResponseSuccess(data=[{
            'pid':i.id,
            'sort':i.sort,
            'time':i.time
        }for i in blogs])

    #通过
    @current_user_is_admin_required
    @data(DataPid())
    def post(self,current_user,data):
        blog =QueryOneInstance(Blog,{'id':data['pid']})
        if not blog:
            return RenderPostNotExist(data['pid'])

        blog.checked = True
        blog.passed = True
        blog.uid_admin=current_user.id
        blog.time_check=NowStr()
        UpdateInstance(blog,data)
        return ResponseSuccess(msg="设置通过成功")


    @current_user_is_admin_required
    @data({**DataText(),**DataPid()})
    def delete(self,current_user,data):
        blog = QueryOneInstance(Blog, {'id': data['pid']})
        if not blog:
            return RenderPostNotExist(data['pid'])

        blog.checked = True
        blog.passed = False
        blog.reason=data['text']
        blog.uid_admin = current_user.id
        blog.time_check = NowStr()
        UpdateInstance(blog, data)
        return ResponseSuccess(msg="设置不通过成功")

class AdminDisable(Resource):
    @current_user_is_admin_required
    @data({**DataDisableUntil(),**DataUid()})
    def post(self,data,current_user):
        user = QueryOneInstance(User, {'id': data['uid']})
        if not user:
            return RenderPostNotExist(data['uid'])
        user.disable_until=data['until']
        return ResponseSuccess(msg="封禁用户成功")

    @current_user_is_admin_required
    @data(DataUid())
    def delete(self,current_user,data):
        user = QueryOneInstance(User, {'id': data['uid']})
        if not user:
            return RenderPostNotExist(data['uid'])
        user.disable_until=None
        return ResponseSuccess(msg="解禁用户成功")